﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace CSSAdriverapp
{
    /// <summary>
    /// Interaction logic for GenerateEvents.xaml
    /// </summary>
    public partial class GenerateEvents : Window
    {
        int term = new int();
        int count = new int();
        BackgroundWorker worker = new BackgroundWorker();  

        public GenerateEvents()
        {
            InitializeComponent();
        }

        private void generateButton_Click(object sender, RoutedEventArgs e)
        {

            if (semesterComboBox.SelectedValue != null && yearTextBox.Text != "" && IsTextAllowed(yearTextBox.Text))
            {
                missingFieldsWarningLabel.Visibility = System.Windows.Visibility.Hidden;
                term = getTerm((string)semesterComboBox.SelectionBoxItem,yearTextBox.Text); //gets id of selected term
                if (term == 0)
                {
                    termDoesNotExistLabel.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    termDoesNotExistLabel.Visibility = System.Windows.Visibility.Hidden;

                    //Message box code
                    string message = "Are you sure? This action will delete all past data. Do not close window while process is running.";
                    string caption = "Confirmation";
                    MessageBoxResult result = MessageBox.Show(message, caption,
                                             MessageBoxButton.YesNo,
                                             MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        generateButton.Visibility = System.Windows.Visibility.Hidden;
                        statusLabel.Visibility = System.Windows.Visibility.Visible;

                        try
                        {
                            StartWork();//Start doing the long update
                        }
                        catch(Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                    
                }
            }
            else
            {
                missingFieldsWarningLabel.Visibility = System.Windows.Visibility.Visible;
                termDoesNotExistLabel.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        //---------------------------------------------------------------------
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            deletePrevious();
            
            //-----assign dates 
            DataClassesDataContext db = new DataClassesDataContext();
            //get  activities
            IQueryable<COMSERV_ACTIVITY> activitie = (from c in db.COMSERV_ACTIVITies
                                                       where c.semester_yearid == term
                                                       select c);
            count = activitie.Count();
            List<COMSERV_ACTIVITY> activities = activitie.ToList();

            foreach (COMSERV_ACTIVITY c in activities)
            {

                List<DateTime> dt = new List<DateTime>();
                // Difference in days, hours, and minutes.
                TimeSpan ts = (DateTime)c.end_date - (DateTime)c.begin_date;
                // Difference in days.
                int differenceInDays = ts.Days;


                DateTime beginning = new DateTime();
                beginning = (DateTime)c.begin_date;
                List<String> days = new List<String>();

                if (c.needed == "Weekly" || c.needed == "BiWeekly")
                {
                    //which days service is
                    if (c.sun == true) { days.Add("Sunday"); }
                    if (c.mon == true) { days.Add("Monday"); }
                    if (c.tue == true) { days.Add("Tuesday"); }
                    if (c.wed == true) { days.Add("Wednesday"); }
                    if (c.thurs == true) { days.Add("Thursday"); }
                    if (c.fri == true) { days.Add("Friday"); }
                    if (c.sat == true) { days.Add("Saturday"); }

                    //weekly
                    for (int i = 0; i < differenceInDays + 1; i++)
                    {
                        if (days.Contains(beginning.DayOfWeek.ToString()))
                        {
                            dt.Add(beginning);
                        }
                        beginning = beginning.AddDays(1);
                    }
                    addDates(dt, c.activityid, days.Count());
                    
                }
                else
                {
                    //dt.Add(beginning);
                    //addDates(dt, c.activityid, days.Count());
                }
                worker.ReportProgress(1);
            }
        }

        private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Hide your wait dialog
            this.Close();
        }

        private void StartWork()
        {
            progressBar.Visibility = System.Windows.Visibility.Visible;
            worker.DoWork += DoWork;
            worker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            worker.WorkerReportsProgress = true;
            worker.RunWorkerCompleted += WorkerCompleted;
            worker.RunWorkerAsync();
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // The progress percentage is a property of e
            progressBar.Maximum = count;
            progressBar.Value++;
        }

        //------------------------------------------------

        private static bool IsTextAllowed(string text) // Makes sure its a number
        {
            Regex regex = new Regex("[^0-9]+"); //regex that matches disallowed text
            return !regex.IsMatch(text);
        }

        private void deletePrevious()
        {
            DataClassesDataContext db = new DataClassesDataContext();
            db.ExecuteCommand("Truncate Table dbo.Event");
        }

        private static int getTerm(String csemester, String cyear)
        {
            DataClassesDataContext db = new DataClassesDataContext();

            IQueryable<int> whichYearL = from c in db.COMSERV_SEMESTER_YEARs
                                                          where c.semester == csemester && c.year == cyear
                                                          select c.semester_yearid;
            whichYearL.ToList();

            if (whichYearL.Count() != 0)
            {
                return whichYearL.First();
            }

            return 0;
        }

        private void addDates(List<DateTime> exactDays, int ID, int numdays)
        {
            DataClassesDataContext db = new DataClassesDataContext();

            foreach (DateTime c in exactDays)
            {
                //AssignOneTimeVans van = new AssignOneTimeVans();
              
                Event eday = new Event{Date = c.Date, ServiceID = ID};
                db.Events.InsertOnSubmit(eday);
                try
                {
                    db.SubmitChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    db.SubmitChanges();
                }
            }
        }
      
    }
}
